-- vim:set et sw=4 sts=4:


math.randomseed(os.time())


function gen_new_field (fldlen, fldwid)
    local field = { n = fldlen }
    local i = 2
    while i < fldlen - 1 do
        local con = math.random(1, fldwid)
        local adj = math.random(2)
        if adj == 1 and con > 1 or con == fldwid then
            table.insert(field, {i,con,con - 1})
        else
            table.insert(field, {i,con,con + 1})
        end
        i = i + math.random(1, 4)
    end
    --for i in ipairs(field) do io.stderr:write(string.format("{%d,%d,%d} ", field[i][1], field[i][2], field[i][3])) end io.stderr:write('\n')
    return field
end


function play_the_game (field, track)
    for evt = 1, #field do
        if field[evt][2] == track then
            track = field[evt][3]
        elseif track == field[evt][3] then
            track = field[evt][2]
        end
    end
    return track
end


function main (fieldwidth, gamescount, gamelength)
    freq = {}
    for i = 1, fieldwidth do freq[i] = {} for j = 1, fieldwidth do freq[i][j] = 0 end end
    for gameno = 1, gamescount do
        local F = gen_new_field(gamelength, fieldwidth)
        for starttrk = 1, fieldwidth do
            local fintrk = play_the_game(F, starttrk)
            freq[starttrk][fintrk] = freq[starttrk][fintrk] + 1
        end
    end

    freq_pct = {}
    for i = 1, fieldwidth do
        freq_pct[i] = {}
        local rowsum = 0
        for j = 1, fieldwidth do
            rowsum = rowsum + freq[i][j]
        end
        for j = 1, fieldwidth do
            freq_pct[i][j] = freq[i][j] / rowsum
        end
    end

    for i = 1, fieldwidth do
        io.output():write(string.format("%2d :\t%s\n", i, table.concat(freq_pct[i], ' , ')))
    end
end


if type(arg) == 'table' then
    main(tonumber(arg[1]) or 10, tonumber(arg[2]) or 1000, tonumber(arg[3]) or 100)
else
    main(10, 1000, 100)
end
